<?php

namespace App\Http\Controllers;

use Cache;
use Illuminate\Http\Request;
use App\Libs\WeChat;

//use EasyWeChat\Message\Article;

class WeChatController extends Controller {

    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public $wechat;
    public $expire;
    public $limitCall;

    public function __construct() {
        $weChatObj = new WeChat;
        $this->wechat = $weChatObj->getWeChat();
    }

    public function getIndex() {
        $weChatObj = new WeChat;
        $weChatObj->evcentHandle();
        $menu = $weChatObj->wechat->menu;
        $buttons = $weChatObj->getButtons();
        $menu->add($buttons);
        return $weChatObj->wechat->server->serve();
    }

    public function getTest() {
        $url = 'wechat/test';
        $weChatObj = new WeChat;
        $oauth = $weChatObj->getWeChat()->oauth;
        session_start();
        if (!Cache::has(session_id())) {
            Cache::put('target_url', $url, $this->expire);
            return $oauth->redirect();
        }
        $user = (object) Cache::get(session_id()); // user 包括openid,name,nickname,sex,country,provice,city,avatar:头像的网址  
        dd($user);
        return view($url)->with('user', $user);
    }



    public function callback(Request $request) {
        $weChatObj = new WeChat;
        $oauth = $weChatObj->getWeChat()->oauth;
        $user = $oauth->user();
        if (is_null($user->id)) {
            $request->session()->forget('session_id');
            $response = $oauth->oauth->scopes(['snsapi_userinfo'])
                    ->redirect();
            return $response;
        }
        $request->session()->put('session_id', $user->toArray());
        return redirect(url(Cache::get('target_url')));
    }

}
